//
//  WebViewController.swift
//  test-ios
//
//  Created by wyz5204 on 2023/4/7.
//

import Foundation
import UIKit
import RxSwift
import RxCocoa
import WebKit

class MVVMWebViewController : MVVMBaseViewController<MVVMWebViewModel>{
    
    
    lazy var rightBarButton: UIBarButtonItem = {
        let view = UIBarButtonItem(image:UIImage.init(named: "icon_navigation_web"), style: .done, target: nil, action: nil)
        return view
    }()
    
    lazy var goBackBarButton: UIBarButtonItem = {
        let view = UIBarButtonItem(image: UIImage.init(named: "icon_navigation_back"), style: .done, target: nil, action: nil)
        return view
    }()
    
    lazy var goForwardBarButton: UIBarButtonItem = {
        let view = UIBarButtonItem(image: UIImage.init(named: "icon_navigation_forward"), style: .done, target: nil, action: nil)
        return view
    }()
    
    lazy var stopReloadBarButton: UIBarButtonItem = {
        let view = UIBarButtonItem(image: UIImage.init(named: "icon_navigation_refresh"), style: .done, target: nil, action: nil)
        return view
    }()
    
    lazy var webView: WKWebView = {
        let view = WKWebView()
        view.navigationDelegate = self
        view.uiDelegate = self
        view.allowsBackForwardNavigationGestures = true
        return view
    }()
    
    lazy var spaceBarButton = {
        return UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
    }()
    
    lazy var toolbar: UIToolbar = {
        let view = UIToolbar()
        view.items = [self.goBackBarButton, self.goForwardBarButton, self.spaceBarButton, self.stopReloadBarButton]
        return view
    }()
    
    
    override func initView(_ contentView: UIView) {
        
        navigationItem.rightBarButtonItem = rightBarButton
        
        toolbar.addTo(contentView) { view in
            view.snp.makeConstraints { make in
                make.bottom.equalToSuperview()
                make.width.equalToSuperview()
            }
        }
        
        webView.addTo(contentView) { view in
            view.snp.makeConstraints { make in
                make.width.equalToSuperview()
                make.top.equalToSuperview()
                make.bottom.equalTo(toolbar.snp.top)
            }
        }
    }
    
    override func bindViewModel(_ viewModel: MVVMWebViewModel) {
        super.bindViewModel(viewModel)
        
        rightBarButton.rx.tap.asObservable().subscribe(onNext: { [weak viewModel] () in
            if let url = viewModel?.url.value {
                print(url)
            }
        }).disposed(by: rx.disposeBag)
        
        viewModel.url.map { $0.absoluteString }.asObservable().bind(to: navigationItem.rx.title).disposed(by: rx.disposeBag)
        
        goBackBarButton.rx.tap.asObservable().subscribe(onNext: { [weak self] () in
            self?.webView.goBack()
        }).disposed(by: rx.disposeBag)
        
        goForwardBarButton.rx.tap.asObservable().subscribe(onNext: { [weak self] () in
            self?.webView.goForward()
        }).disposed(by: rx.disposeBag)
        
        stopReloadBarButton.rx.tap.asObservable().subscribe(onNext: { [weak self] () in
            if let webView = self?.webView {
                if webView.isLoading {
                    webView.stopLoading()
                } else {
                    webView.reload()
                }
            }
        }).disposed(by: rx.disposeBag)
    }
    
    override func updateView(){
        guard let url = viewModel?.url.value else {
            return
        }
        goBackBarButton.isEnabled = webView.canGoBack
        goForwardBarButton.isEnabled = webView.canGoForward
        stopReloadBarButton.image = webView.isLoading ? UIImage.init(named:"icon_navigation_stop") : UIImage.init(named: "icon_navigation_refresh")
        webView.load(URLRequest(url: url))
    }
    
}

extension MVVMWebViewController: WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        print("didCommit >> \(webView)")
        if let url = webView.url{
            self.viewModel?.url.accept(url)
        }
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {print("didFinish >> \(webView)")
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {print("didFail >> \(webView)")
    }
}

extension MVVMWebViewController: WKUIDelegate {
    
}

class MVVMWebViewModel : MVVMBaseViewModel{
    
    let url :BehaviorRelay<URL>
    
    init(_ url : URL) {
        self.url = BehaviorRelay<URL>(value : url)
        super.init()
    }
}
